import axios from 'axios'
import { Loading, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import { router } from '@/router'

// loading对象
let loading

// 当前正在请求的数量
let needLoadingRequestCount = 0

// 显示loading
function showLoading(target) {
  // 后面这个判断很重要，因为关闭时加了抖动，此时loading对象可能还存在，
  // 但needLoadingRequestCount已经变成0.避免这种情况下会重新创建个loading
  if (needLoadingRequestCount === 0 && !loading) {
    loading = Loading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(255, 255, 255, 0.5)',
      target: target || 'body'
    })
  }
  needLoadingRequestCount++
}

// 隐藏loading
function hideLoading() {
  needLoadingRequestCount--
  needLoadingRequestCount = Math.max(needLoadingRequestCount, 0) // 做个保护
  if (needLoadingRequestCount === 0) {
    // 关闭loading
    toHideLoading()
  }
}

// 关闭loading
var toHideLoading = () => {
  loading.close()
  loading = null
}

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // 判断当前请求是否设置了不显示Loading
    if (config.headers.showLoading !== false) {
      showLoading(config.headers.loadingTarget)
    }
    if (store.getters.token) {
      config.headers['Token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
const toLogin = () => {
  router.replace({
    path: '/login'
  })
}
// response interceptor
service.interceptors.response.use(
  response => {
    hideLoading()
    const res = response.data
    // code不存在
    if (!res.code) {
      return res
    }
    // 如果自定义代码不是200，则判断为错误。
    if (res.code === 200) {
      return res
    }
    if (res.code === 401) {
      removeToken()
      toLogin()
      Message(res.msg, 'error')
    } else {
      Message(res.msg, 'error')
      return Promise.reject(res)
    }
  },
  error => {
    hideLoading()
    Message('请求出错', 'error')
    return Promise.reject(error)
  }
)

export default service
